//
//  OtherCityViewModel.swift
//  EarbudsCommon
//
//  Created by 李然 on 2024/5/8.
//

import Foundation
import RxSwift
import RxCocoa
import RxDataSources

public class OtherCityCellViewModel: ViewModel {
    public let cityName: String
    public let isSelect: Bool
    public init(cityName: String, isSelect: Bool) {
        self.cityName = cityName
        self.isSelect = isSelect
    }
}

public enum OtherCitySectionItem {
    case auto(cellModel: DefaultSwitchCellViewModel)
    case location(cellModel: DefaultCellViewModel)
    case city(cellModel: OtherCityCellViewModel)
}

public struct OtherCitySectionModel {
    public var headerTitle: String
    public var items: [OtherCitySectionItem]
}

extension OtherCitySectionModel: SectionModelType {
    public init(original: OtherCitySectionModel, items: [OtherCitySectionItem]) {
        self = original
        self.items = items
    }
}

public class OtherCityViewModel: ViewModel {
    
    public let dataSource = BehaviorRelay<[OtherCitySectionModel]>(value: [])

    var cellDisposeBag = DisposeBag()
    
    public override init() {
        super.init()
        
        Observable.combineLatest(Weather.shared.autoGPSEnable, Weather.shared.cityName)
            .map { [weak self] auto, area in
                guard let self = self else { return [] }
                self.cellDisposeBag = DisposeBag()
                var citySections: [OtherCitySectionModel] = []
                
                let autoCellViewModel = DefaultSwitchCellViewModel(isEnabel: auto)
                autoCellViewModel.switchChanged.skip(1).bind(to: Weather.shared.autoGPSEnable).disposed(by: self.cellDisposeBag)
                
                let areaCellViewModel = DefaultCellViewModel(detail: area)
                
                citySections.append(OtherCitySectionModel(headerTitle: "", items: [.auto(cellModel: autoCellViewModel),
                                                                                   .location(cellModel: areaCellViewModel)]))
                
                if !auto {
                    let letters = City.headers
                    let cityNames: [[String]] = City.list
                    for (i, letter) in letters.enumerated() {
                        if cityNames.count > i {
                            let models = cityNames[i].map{ OtherCityCellViewModel.init(cityName: $0, isSelect: area == $0) }
                            let section = OtherCitySectionModel(headerTitle: letter, items: models.map{ .city(cellModel: $0) })
                            citySections.append(section)
                        }
                    }
                }
                return citySections
            }
            .bind(to: dataSource).disposed(by: rx.disposeBag)
    }
}
